const path = require('path');
const {generateSha1ByBasename} = require("../util/hash");
const {getBasenameWithoutExt} = require("../util/file");
class RouteMapper {
    mapFilesToRoutes(files, vaultConfig) {
        return files.map(file => {
            // const routePath = this.generateRoutePath(file, vaultConfig);
            const [routePath, routeName] = this.generateRouteHash(file, vaultConfig);
            const fileType = this.getFileType(file.path);

            return {
                filePath: file.path,
                mtime: file.mtime,
                prefix: vaultConfig.name,
                route: routePath,
                description: routeName,
                handler: vaultConfig.handler || this.determineHandler(fileType),
                type: fileType,
                vault: vaultConfig.name
            };
        });
    }
    generateRouteHash(file, vaultConfig) {
        let route = file.relativePath.replace(/\\/g, '/');

        // 移除扩展名
        route = route.replace(/\.[^/.]+$/, '');
        // const hashMatch = route.match(/__([a-f0-9]+)/);
        const hashMatch = path.basename(route).match(/([^/]*)__([a-f0-9]+)/);
        let routeName = "";
        let routeHash = "";
        if (hashMatch) {
            routeName = hashMatch[1];
            routeHash = hashMatch[2];
        } else {
            // routeName = path.basename(file.path)
            routeName = getBasenameWithoutExt(path.basename(file.path));
            routeHash = generateSha1ByBasename(routeName);
        }
        return [`/${routeHash}`, `${routeName}`];

    }

    generateRoutePath(file, vaultConfig) {
        let route = file.relativePath.replace(/\\/g, '/');

        // 移除扩展名
        route = route.replace(/\.[^/.]+$/, '');

        // 处理特殊模式（如vault2的hash提取）
        if (vaultConfig.pattern.toString().includes('__')) {
            const hashMatch = route.match(/__([a-f0-9]+)/);
            if (hashMatch) {
                route = route.replace(/__[a-f0-9]+/, '');
            }
        }

        // 清理路径中的特殊字符
        route = route.replace(/\/+/g, '/').replace(/^\/|\/$/g, '');

        return `/${route}`.replace(/\/+/g, '/');
    }

    getFileType(filePath) {
        const ext = path.extname(filePath).toLowerCase();
        if (['.md', '.markdown'].includes(ext)) return 'markdown';
        if (['.html', '.htm'].includes(ext)) return 'html';
        if (['.mp4', '.avi', '.mkv', '.mov', '.wmv'].includes(ext)) return 'video';
        return 'file';
    }

    determineHandler(fileType) {
        const handlerMap = {
            markdown: 'markdown',
            html: 'html',
            video: 'video',
            file: 'static'
        };
        return handlerMap[fileType] || 'static';
    }
}

module.exports = RouteMapper;